from datetime import datetime
from typing import Annotated
from sqlalchemy.orm import (
    DeclarativeBase,
    Mapped,
    MappedAsDataclass,
    declared_attr,
    mapped_column,
)


id_key = Annotated[
    int,
    mapped_column(primary_key=True, index=True, autoincrement=True, comment="主键ID"),
]


class UserMixin(MappedAsDataclass):
    create_user: Mapped[int] = mapped_column(comment="创建者")
    update_user: Mapped[int | None] = mapped_column(
        init=False,
        default=None,
        comment="更新者",
    )


class DatetimeMixin(MappedAsDataclass):
    create_time: Mapped[datetime] = mapped_column(
        init=False,
        default_factory=datetime.now,
        comment="创建时间",
    )
    update_time: Mapped[datetime | None] = mapped_column(
        init=False,
        onupdate=datetime.now,
        comment="更新时间",
    )


class MappedBase(DeclarativeBase):
    @declared_attr.directive
    def __tablename__(cls) -> str:
        return cls.__name__.lower()


class DataClassBase(MappedAsDataclass, MappedBase):
    __abstract__ = True


class Base(DataClassBase, DatetimeMixin):
    __abstract__ = True
